import { isMp } from './platform'

/**
 * 根据微信小程序当前环境，判断应该获取的BaseUrl
 */
export const getEvnBaseUrl = () => {
  // 请求基准地址
  let baseUrl = import.meta.env.VITE_SERVER_BASEURL
  // 小程序端环境区分
  if (isMp) {
    const {
      miniProgram: { envVersion },
    } = uni.getAccountInfoSync()

    switch (envVersion) {
      case 'develop':
        // TODO 测试时使用本机h5启动地址
        baseUrl = 'http://192.168.1.15:9000'
        break
      case 'trial':
        baseUrl = 'https://trial.test.net'
        break
      case 'release':
        baseUrl = 'https://prod.test.net'
        break
    }
  }

  return baseUrl
}

/**
 * 手动转base64，适配微信小程序
 *
 * @export
 * @param {*} str
 * @return {*}
 */
export function base64Encode(str) {
  const CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
  let out = ''
  let i = 0
  const len = str.length
  let c1
  let c2
  let c3
  let enc1
  let enc2
  let enc3
  let enc4
  while (i < len) {
    c1 = str.charCodeAt(i++)
    c2 = str.charCodeAt(i++)
    c3 = str.charCodeAt(i++)
    enc1 = c1 >> 2
    enc2 = ((c1 & 3) << 4) | (c2 >> 4)
    enc3 = ((c2 & 15) << 2) | (c3 >> 6)
    enc4 = c3 & 63
    if (isNaN(c2)) {
      enc3 = enc4 = 64
    } else if (isNaN(c3)) {
      enc4 = 64
    }
    out += CHARS.charAt(enc1) + CHARS.charAt(enc2) + CHARS.charAt(enc3) + CHARS.charAt(enc4)
  }
  return out
}
